package xq.gwt.ui.crud;

import xq.gwt.mvc.model.AbstractCommandModel;
import xq.gwt.mvc.model.PersistableEntityModel;
import xq.gwt.ui.crud.localization.CrudDictionary;
import xq.gwt.ui.rpc.AsyncCallbackAdapter;
import xq.gwt.ui.widgets.feedback.FeedbackService;

public class RefreshEntityCommand extends AbstractCommandModel {	
	private static final long serialVersionUID = 484799594606381137L;
	private EntityEditorModel editorModel;

	public RefreshEntityCommand(EntityEditorModel editorModel){
		this.editorModel = editorModel;
	}
	
	@Override
	public void execute() throws Exception {
		if(editorModel == null){
			return;
		}
		
		PersistableEntityModel entity = editorModel.getEntity(); 
		if (entity  == null || entity.isNew()){
			return;
		}
		PersistableEntityModel dtoEntity = entity.copy();
		CrudServiceProvider.persistanceService.fetchEntity(dtoEntity,new EntityFetched()); 
		FeedbackService.getFeedbackPresenter().showFeedback(CrudDictionary.Constants().fetching_data_msg());

	}
	
	private class EntityFetched extends AsyncCallbackAdapter<PersistableEntityModel> {

		@Override
		public void onSuccess(PersistableEntityModel result) {
			if(editorModel != null){
				editorModel.setEntity(result);
			}			
			FeedbackService.getFeedbackPresenter().showFeedback(null);
		}
		
	}
	

	public EntityEditorModel getEditorModel() {
		return editorModel;
	}

	public void setEditorModel(EntityEditorModel editorModel) {
		this.editorModel = editorModel;
	}

	@Override
	public String getCaption() {
		return CrudDictionary.Constants().refresh_caption();		
	}
	
	

}
